import cv2
import numpy as np


def on_trackbar(val):
    pass


# 创建滑动条窗口
cv2.namedWindow("Threshold Adjustments")
# 读取原图
image = cv2.imread("D:/temp/d4/p1.png")
# 获得图像的尺寸
height, width, _ = image.shape
# 将图像转换为HSV颜色空间
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 设定初始蓝色的阈值范围
init_lower_blue = [0, 0, 0]
init_upper_blue = [255, 255, 255]
# 创建滑动条，设置回调函数
cv2.createTrackbar(
    "Lower H", "Threshold Adjustments", init_lower_blue[0], 179, on_trackbar
)
cv2.createTrackbar(
    "Lower S", "Threshold Adjustments", init_lower_blue[1], 255, on_trackbar
)
cv2.createTrackbar(
    "Lower V", "Threshold Adjustments", init_lower_blue[2], 255, on_trackbar
)
cv2.createTrackbar(
    "Upper H", "Threshold Adjustments", init_upper_blue[0], 179, on_trackbar
)
cv2.createTrackbar(
    "Upper S", "Threshold Adjustments", init_upper_blue[1], 255, on_trackbar
)
cv2.createTrackbar(
    "Upper V", "Threshold Adjustments", init_upper_blue[2], 255, on_trackbar
)
while True:
    # 获取滑动条的当前值
    lower_hue = cv2.getTrackbarPos("Lower H", "Threshold Adjustments")
    lower_saturation = cv2.getTrackbarPos("Lower S", "Threshold Adjustments")
    lower_value = cv2.getTrackbarPos("Lower V", "Threshold Adjustments")
    upper_hue = cv2.getTrackbarPos("Upper H", "Threshold Adjustments")
    upper_saturation = cv2.getTrackbarPos("Upper S", "Threshold Adjustments")
    upper_value = cv2.getTrackbarPos("Upper V", "Threshold Adjustments")
    # 设定蓝色的阈值范围
    lower_blue = np.array([lower_hue, lower_saturation, lower_value])
    upper_blue = np.array([upper_hue, upper_saturation, upper_value])
    # 根据阈值范围分割图像
    mask = cv2.inRange(hsv_image, lower_blue, upper_blue)
    result = cv2.bitwise_and(image, image, mask=mask)
    # 显示原图和结果图像
    cv2.imshow("Original Image", image)
    cv2.imshow("Result Image", result)
    # 按下ESC键退出循环
    key = cv2.waitKey(1) & 0xFF
    if key == 27:
        break
# 关闭窗口
cv2.destroyAllWindows()
